wilcoxon
Statistics Timm Feb10 Revised

Wilcoxon Tests (paired)

Problem
=======

Determine if two populations of numbers (of equal size), are
statistically different.  Compute the difference of each pair (a pair
is two items from the same position in both population), rank those
differences, and check the signficance of those ranked differences.

Solution
========

 function wilcoxon(pop1,pop2,up,critical,	\
		   ranks,w0,w,correction,z,sigma,\
                   i, delta, n,diff,absDiff) {
     for(i in pop1) {
	 delta = pop1[i] - pop2[i]
	 if (delta) { 
	     n++
	     diff[i]    = delta
	     absDiff[i] = abs(delta) 
	 }
     }
     rank(absDiff,ranks)
     for(i in absDiff)  {
	 w0 = ranks[absDiff[i]] 
	 w += (diff[i] < 0)  ? -1*w0  :  w0
     }
     sigma = sqrt((n*(n+1)*(2*n+1))/6)
     z = (w - 0.5) / sigma; 
     if (z >= 0 && z <= critical) 
	 return 0
     else  
	 return up ? w : -1*w
 }
 function criticalValue(conf) {
     conf = conf ? conf  : 95
     if (conf==99) return 2.326
     if (conf==95) return 1.960 
     if (conf==90) return 1.645
 }

   function Wilcoxon() {
       print "1,  1 " wilcoxon1(1,1)
       print "0.5,1 " wilcoxon1(0.5,1)
       print "2,  1 " wilcoxon1(2,1)
       print "1,  0 " wilcoxon1(1,0)
       print "0.5,0 " wilcoxon1(0.5,0)
       print "2,  0 "  wilcoxon1(2,0)
   }
   function wilcoxon1(mult,up,       pop1,pop2,out,i) {
       mult= mult ? mult : 1
       s2a("1 78 2 24 3 64 " \
	   "4 45 5 64 6 52 "  \
	   "7 30 8 50 9 64 "   \
	   "10 50 11 78 12 22 "	\
	   "13 84 14 40 15 90 "	\
	   "16 72" ,pop1, " ")
       s2a("1 78 2 24 3 62 " \
	   "4 48 5 68 6 56 "  \
	   "7 25 8 44 9 56 "   \
	   "10 40 11 68 12 36 "	\
	   "13 68 14 20 15 58 "	\
	   "16 32",pop2," ")
       for(i in pop1) pop1[i] *= mult
       out = wilcoxon(pop1,pop2,up,criticalValue(95))
       if (out == 0)
	   return "tie"
       else if (out > 0)
	   return "win for a"
       else if (out < 0)
	   return "loss for a"
   }
		   
Author
======

Tim Menzies

